package com.gurun.codes.contract.base;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.gurun.base.Logger;
import com.gurun.codes.App;
import com.gurun.codes.R;
import com.gurun.codes.contract.base.view.RxView;
import com.gurun.codes.utils.Constants;
import com.gurun.codes.utils.DateTimeUtils;
import com.gurun.model.base.ResultObserver;
import com.gurun.model.base.RetrofitManager;
import com.gurun.model.bean.AlarmListBean;
import com.gurun.model.bean.ApiResult;
import com.gurun.model.bean.common.DateTimeModel;
import com.gurun.model.bean.common.GetDeviceAlarmInfoListRequestBean;
import com.gurun.model.bean.common.GetDeviceAlarmInfoListResultBean;
import com.gurun.model.bean.common.ListContentModel;
import com.gurun.model.bean.common.ListTitleModel;
import com.gurun.model.bean.door_window.GetDoorWindowInfoResultBean;
import com.gurun.model.service.CommonService;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;

/**
 * 专门为报警记录抽取出来,本地对服务器数据做分组处理
 *
 * @param <V>
 */
public abstract class BaseAlarmListPresenter<V extends RxView> extends BasePresenter<V> {
    protected List<Object> mFinalDatas = new ArrayList<>();//页面上需要的数据
    protected LinkedHashMap<String, List<DateTimeModel>> mDatasMap = new LinkedHashMap<>();
    protected int mCurrentPageForLocal = 1;//当前显示的第几页
    protected static final int PAGE_SIZE = 8;//页面上每页显示多少条

    /**
     * 将列表数据处理成真正需要的格式
     * <p>
     * 将时间解析成model，将相同日期的装进同一个map中map的veluse是list，将map转成list，key为时间title，velue为值，
     * 页面从这个list中每次取相同个数的数据作为页面显示（记录当前取的第几页，是否已经将服务器数据获取完，如果获取完就不用去服务器获取），如果不够就去网络请求。
     */
    public void parseServerDatas(List<AlarmListBean> alarmListBeans) {
        if (alarmListBeans != null) {
            //第一步将数据放入map

            for (AlarmListBean item : alarmListBeans) {
                String timeString = item.getAlarmTime();
                if (!TextUtils.isEmpty(timeString)) {
                    DateTimeModel dateTimeModel = parseDateTimeString(timeString);
                    dateTimeModel.setMessage(item.getAlarmContent());
                    String mapKey = dateTimeModel.getYear() + "-" + dateTimeModel.getMonth() + "-" + dateTimeModel.getDay();
                    if (mDatasMap.containsKey(mapKey)) {
                        mDatasMap.get(mapKey).add(dateTimeModel);
                    } else {
                        List<DateTimeModel> listBeans = new ArrayList<>();
                        listBeans.add(dateTimeModel);
                        mDatasMap.put(mapKey, listBeans);
                    }
                }
            }
            //第二步将map装入list
            if (mDatasMap.size() > 0) {
                mFinalDatas.clear();
                for (String key : mDatasMap.keySet()) {
                    List<DateTimeModel> dateTimeModels = mDatasMap.get(key);
                    if (dateTimeModels != null && dateTimeModels.size() > 0) {
                        DateTimeModel dateTimeModel = dateTimeModels.get(0);
                        ListTitleModel listTitleModel = new ListTitleModel(dateTimeModel.getMonth(), dateTimeModel.getDay(), dateTimeModel.getWeek());
                        mFinalDatas.add(listTitleModel);
                        for (DateTimeModel item : dateTimeModels) {
                            ListContentModel listContentModel = new ListContentModel(item.getHour() + ":" + (item.getMinute() >= 10 ? item.getMinute() : "0" + item.getMinute()), item.getMessage());
                            if (mFinalDatas.size() == 1) {//如果是第一条内容
                                listContentModel.setFirstItem(true);
                            } else {
                                listContentModel.setFirstItem(false);
                            }
                            mFinalDatas.add(listContentModel);
                        }
                    }
                }
            }
        }
    }

    private DateTimeModel parseDateTimeString(String dateTimeString) {
        try {
            if (!TextUtils.isEmpty(dateTimeString)) {
                DateTimeModel dateTimeModel = DateTimeUtils.parseDateTimeToModel(dateTimeString);
                return dateTimeModel;
            }
        } catch (Exception e) {
            Logger.e(e.getMessage());
        }
        return null;
    }

    /**
     * 是否已经是第一页
     *
     * @return
     */
    public boolean isFirstPage() {
        return mCurrentPageForLocal == 1;
    }


    //============================公共请求报警记录的方法================================
    protected abstract void onMLoading();

    protected abstract void onMLoaded(GetDeviceAlarmInfoListResultBean datas);

    protected abstract void onMError(String msg);

    protected abstract void onMComplete();

    protected abstract void mResetListDatas();

    protected Context mContext;

    private String mLastRefreshTime;//最后刷新时间
    private static int TOTAL_COUNTER = 0;//服务器端一共多少条数据
    private static int mPageCount = 0;
    private int mCurrentPage = 1;//当前页

    private String getRefreshTime() {
        if (TextUtils.isEmpty(mLastRefreshTime)) {
            mLastRefreshTime = "0";
        }
        return mLastRefreshTime;
    }

    private void setRefreshTime(String currentTime) {
        mLastRefreshTime = currentTime;
    }

    public void getDeviceAlarmInfo(long deviceId, int timeFlag) {
        GetDeviceAlarmInfoListRequestBean requestBean = new GetDeviceAlarmInfoListRequestBean();
        requestBean.setVersion(Constants.HTTP_VERSION);
        requestBean.setUserId(App.getInstance().getLoginUserId());
        requestBean.setToken(App.getInstance().getLoginToken());
        requestBean.setPageNo(mCurrentPage);
        requestBean.setPageSize(Constants.PAGE_SIZE);
        requestBean.setRefreshTime(getRefreshTime());
        requestBean.setDeviceId(deviceId);
        requestBean.setTimeFlag(timeFlag);

        RetrofitManager.getInstance().createApiService(CommonService.class)
                .getDeviceAlarmInfo(requestBean)
                .compose(getView().<GetDeviceAlarmInfoListResultBean>bindToLifecycleDestroy())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe((new ResultObserver<GetDeviceAlarmInfoListResultBean>() {

                    @Override
                    public void onLoading(Disposable d) {
                        onMLoading();
                    }

                    @Override
                    public void onOtherError(Throwable e) {
                        onMError(mContext.getString(R.string.common_connect_server_failed));
                    }

                    @Override
                    public void onLoaded() {
                        onMComplete();
                    }

                    @Override
                    public void onSuccess(GetDeviceAlarmInfoListResultBean result, String msg) {
                        if (result != null) {
                            if (mCurrentPage == 1) {
                                mResetListDatas();
                            }
                            TOTAL_COUNTER = result.getTotalCount();
                            mPageCount = result.getPageCount();

                            if (result.getAlarmList() != null && result.getAlarmList().size() > 0) {
                                onMLoaded(result);
                                mCurrentPage++;
                                setRefreshTime(result.getRefreshTime());
                            }
                        }
                    }

                    @Override
                    public void onApiError(ApiResult result) {
                        if (result != null) {
                            onMError(result.getRetMsg());
                        } else {
                            onMError(mContext.getString(R.string.common_connect_server_failed));
                        }
                    }
                }));
    }

    public void getDeviceAlarmInfo(long deviceId) {
        getDeviceAlarmInfo(deviceId, 0);
    }

    /**
     * 页面上点击下一页or上一页取数据,从mFinalDatas一页一页的取，如果最后一页不足一页的数据，就判断是否需要从服务器获取数据，如果需要
     * 就先从服务器获取，然后在返回给页面
     *
     * @param isNextPage true：下一页
     * @param isPrePage  true：上一页
     *                   除了上一页和下一页就是获取当前页：比如说第一次获取和从服务器返回后自动获取
     */
    public List<Object> getAlarmDatas(boolean isNextPage, boolean isPrePage, long deviceId, int timeFlag) {
        if (isNextPage) {
            mCurrentPageForLocal += 1;
        }
        if (isPrePage) {
            mCurrentPageForLocal -= 1;
        }

        if (mCurrentPageForLocal < 1) {
            mCurrentPageForLocal = 1;
        }

        List<Object> pageDatas = new ArrayList<>();
        int startIndex = (mCurrentPageForLocal - 1) * PAGE_SIZE;
        int endIndex = startIndex + PAGE_SIZE - 1;
        int currentDatasCount = mFinalDatas.size();
        if (currentDatasCount < (endIndex + 1)) {//不足一页，就去服务器获取
            if (mCurrentPage >= mPageCount) {//已经将服务器数据获取完
                if (currentDatasCount >= (startIndex + 1)) {//如果最后一页还有数据，即使不足一页
                    endIndex = currentDatasCount - 1;
                } else {//已经没有数据了,返回null
                    if (isNextPage) {
                        mCurrentPageForLocal -= 1;//将页码回归
                    }
                    return null;
                }
            } else {
                getDeviceAlarmInfo(deviceId, timeFlag);
                return pageDatas;//返回一个size为0的list说明去服务器获取数据了
            }
        }

        for (int i = startIndex; i <= endIndex; i++) {
            pageDatas.add(mFinalDatas.get(i));
        }
        return pageDatas;
    }

    public List<Object> getAlarmDatas(boolean isNextPage, boolean isPrePage, long deviceId) {
        return getAlarmDatas(isNextPage, isPrePage, deviceId, 0);
    }

}
